package com.wang.service;

import com.sun.javaws.IconUtil;
import com.wang.dao.UserDao;
import com.wang.pojo.HomeCost;
import com.wang.pojo.Page;
import com.wang.pojo.User;
import com.wang.utils.JDBCUtils;

import java.util.List;

public class UserService {

    private UserDao userDao = new UserDao();

    public User registUser(User user) {
        System.out.println(user);
        userDao.saveUser(user);
        return login(user);//保存完顺便登录
    }

    public User login(User user) {
        return userDao.queryUserByUsernameAndPassword(user.getUserName(), user.getPassword());
    }

    public boolean existsUsername(String username) {
        if (userDao.queryUserByUsername(username) == null) {
            return false;
        }
        return true;
    }
    public boolean existsName(String name) {
        if (userDao.queryUserByName(name) == null) {
            return false;
        }
        return true;
    }

    public User getUserById(int id){
        return userDao.getUserById(id);
    }

    public User updateUserFace(int id,String face_path){
        userDao.updateUserFace(id,face_path);
        return userDao.getUserById(id);
    }

    public int updateUser(User newUser) {
        return userDao.updateUser(newUser);
    }

    public Page<User> page(int pageNo, int pageSize, User user) {
        Page<User> page = new Page<User>();

        page.setPageSize(pageSize);

        Integer pageTotalCount = userDao.queryForPageTotalCount(user);

        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal = pageTotalCount / pageSize;  //计算总页数

        if (pageTotalCount % pageSize != 0) pageTotal++;    //不能整除要多一页

        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);

        int begin = (page.getPageNo() - 1) * pageSize;  //套用公式计算begin

        List<User> items = userDao.queryForPageItems(begin, pageSize, user);
        page.setItems(items);

        return page;
    }

    public void deleteUserById(int id) {
        userDao.deleteUserById(id);
    }
}
